package com.huluobo.koltinim2003a.ui.fragment

import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.huluobo.koltinim2003a.R
import com.huluobo.koltinim2003a.adapter.ContactListAdapter
import com.huluobo.koltinim2003a.adapter.EMContactListenerAdapter
import com.huluobo.koltinim2003a.base.BaseFragment
import com.huluobo.koltinim2003a.contract.contact.ContactContract
import com.huluobo.koltinim2003a.contract.contact.ContactPresenter
import com.hyphenate.EMContactListener
import com.hyphenate.chat.EMClient
import kotlinx.android.synthetic.main.fragment_contacts.*
import kotlinx.android.synthetic.main.header.*
import org.jetbrains.anko.toast

/**
 * Created by lc on 2022/9/23.
 * 联系人页面
 */
class ContactFragment : BaseFragment(), ContactContract.View {
    override fun getLayoutResId(): Int = R.layout.fragment_contacts

    val presenter = ContactPresenter(this)

    override fun init() {
        super.init()

        headerTitle.text = getString(R.string.contact)
        add.visibility = View.VISIBLE
        //Java中的初始化
//        swipeRefreshLayout.setColorSchemeColors(resources.getColor(R.color.qq_blue))
//        swipeRefreshLayout.isRefreshing = true
//
//        recyclerView.layoutManager = LinearLayoutManager(context)
//        recyclerView.adapter = ContactListAdapter()

        //Kotlin中的初始化
        swipeRefreshLayout.apply {
            setColorSchemeColors(resources.getColor(R.color.qq_blue))
            isRefreshing = true
            setOnRefreshListener {
                presenter.loadContacts()
            }
        }

        recyclerView.apply {
            setHasFixedSize(true)//当RecyclerView的长度发生变化时,内部会做优化处理
            layoutManager = LinearLayoutManager(context)
            adapter = ContactListAdapter(context, presenter.contactListItems)
        }

        presenter.loadContacts()

        EMClient.getInstance().contactManager()
            .setContactListener(object : EMContactListenerAdapter() {
                override fun onContactDeleted(username: String?) {
                    //当页面感知到用户删除好友时,重新获取联系人数据
                    presenter.loadContacts()
                }
            })
    }

    override fun onLoadContactsSuccess() {
        //关闭下拉刷新
        swipeRefreshLayout.isRefreshing = false
        //刷新适配器
        recyclerView.adapter?.notifyDataSetChanged()
    }

    override fun onLoadContactsFailed() {
        //关闭下拉刷新
        swipeRefreshLayout.isRefreshing = false
        //toast提示
        context?.toast(R.string.load_contacts_failed)
    }
}